import 'package:dio/dio.dart';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:dio_cache_interceptor_file_store/dio_cache_interceptor_file_store.dart';
import 'package:path_provider/path_provider.dart' as pp;
import 'package:workmate/models/api.dart';

class HttpManager {
  static const contentTypeJson = 'application/json';
  static const contentTypeForm = 'application/x-www-form-urlencoded';
  late CacheOptions cacheOptions;
  late CacheStore cacheStore;
  final dio = Dio(); // 使用默认配置

  Future fetch<T>(RequestOptions requestOptions) async {
    Map extra = requestOptions.extra;
    bool isparse = extra['isparse'] ?? false;
    var response = await dio.fetch(requestOptions);
    var resultData = response.data;
    var data = resultData['data'];
    // 解析数据并返回
    if (isparse && data != null) {
      data = modelDataHanddle<T>(data);
    }
    return data;
  }

  modelDataHanddle<T>(json) {
    var moduleName = T.toString();
    switch (moduleName) {
      case 'ApiModel':
        return ApiModel.fromJson(json);
      default:
        return json;
    }
  }

  HttpManager() {
    pp.getApplicationDocumentsDirectory().then((dir) {
      cacheStore = FileCacheStore(dir.path);
      cacheOptions = CacheOptions(
        store: cacheStore,
        hitCacheOnErrorExcept: [], // for offline demonstration
      );
      dio.interceptors.add(DioCacheInterceptor(options: cacheOptions));
    });
  }
}
